package com.hmall.search.interceptors;

import com.hmall.search.utils.ThreadLocalUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.http.HttpStatus;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Slf4j
public class AuthorizationHandlerInterceptor implements HandlerInterceptor {


    //目标HandLer执行之前
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
       //判断authorization请求头是否为空
        String userId = request.getHeader("authorization");
        log.warn("userId:{}",userId);

        if (StringUtils.isNotBlank(userId)){
            //非空绑定到ThreadLocal上，放行
            ThreadLocalUtils.setUseId(userId);
            return true;
        }
        //空，未登录 未认证【401】
        response.setStatus(HttpStatus.SC_UNAUTHORIZED);
        response.setContentType("application/json;charset=UTF-8");
        response.getWriter().write("{\"message\", \"非法用户.禁止访问\"}");
        return false;
       // return HandlerInterceptor.super.preHandle(request, response, handler);
    }


    //渲染视图之后
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        //HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
        ThreadLocalUtils.remove();
    }
}
